using Microsoft.Extensions.Logging;
using SmartCustomerService.Web.Models;

namespace SmartCustomerService.Web.Services;

public interface IAliyunBailianCustomerService
{
    Task<string> ChatAsync(string message, string? context = null);
    Task<List<ChatMessage>> GetChatHistoryAsync();
    Task ClearChatHistoryAsync();
    Task StartNewTopicAsync();
}

public class AliyunBailianCustomerService : IAliyunBailianCustomerService
{
    private readonly IAliyunBailianClient _aliyunClient;
    private readonly ILogger<AliyunBailianCustomerService> _logger;
    private readonly List<ChatMessage> _chatHistory;
    private readonly string _systemPrompt;
    private readonly ISimpleRetrievalService _retrieval;

    // 简易热门问缓存
    private static readonly Dictionary<string, (string answer, DateTime ts)> _hotCache = new();
    private static readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(20);

    public AliyunBailianCustomerService(
        IAliyunBailianClient aliyunClient,
        ILogger<AliyunBailianCustomerService> logger,
        ISimpleRetrievalService retrieval)
    {
        _aliyunClient = aliyunClient;
        _logger = logger;
        _retrieval = retrieval;
        _chatHistory = new List<ChatMessage>();
        
        // 系统提示词
        _systemPrompt = @"你是一个专业的智能客服助手，服务原则：

1) 只基于已知事实与提供的资料回答；不确定时明确说""不确定/暂无相关信息""，不要编造。
2) 回答采用“结论→要点(3-5条)→可选建议”的结构；必要时给澄清问题。
3) 语气礼貌、专业、具亲和力；涉及敏感或越权请求时提示联系人工客服。
4) 如用户提供了上下文资料，请严格以其为准进行回答。
";
    }

    public async Task<string> ChatAsync(string message, string? context = null)
    {
        try
        {
            _logger.LogInformation("Processing customer service request: {Message}", message);

            // 热门问缓存命中
            var cacheKey = (message ?? string.Empty).Trim().ToLowerInvariant();
            if (_hotCache.TryGetValue(cacheKey, out var cached) && (DateTime.Now - cached.ts) < _cacheTtl)
            {
                return cached.answer;
            }

            // 添加用户消息
            var userMessage = new ChatMessage
            {
                Content = message,
                IsUser = true,
                Timestamp = DateTime.Now
            };
            _chatHistory.Add(userMessage);

            // 构建历史（8轮）并排除当前
            var conversationHistory = _chatHistory
                .TakeLast(16)
                .Reverse()
                .Skip(1)
                .Reverse()
                .ToList();

            // 轻量检索召回
            var retrieved = _retrieval.RetrieveRelevantSnippets(message ?? string.Empty, 5);
            var retrievedBlock = retrieved.Count > 0
                ? "\n\n【检索到的相关资料(最多5条)】\n" + string.Join("\n---\n", retrieved)
                : string.Empty;

            // 有上下文则优先
            var effectiveSystemPrompt = _systemPrompt
                + (string.IsNullOrWhiteSpace(context) ? string.Empty : "\n\n【用户提供的上下文资料】\n" + context!.Trim())
                + retrievedBlock;

            // 调用模型
            var aiResponse = await _aliyunClient.ChatAsync(message, effectiveSystemPrompt, conversationHistory);

            // 记录AI消息
            var aiMessage = new ChatMessage
            {
                Content = aiResponse,
                IsUser = false,
                Timestamp = DateTime.Now
            };
            _chatHistory.Add(aiMessage);

            if (_chatHistory.Count > 100)
            {
                _chatHistory.RemoveRange(0, _chatHistory.Count - 100);
            }

            // 写入缓存
            _hotCache[cacheKey] = (aiResponse, DateTime.Now);

            _logger.LogInformation("AI response generated successfully. Length: {Length}", aiResponse.Length);
            return aiResponse;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error in customer service chat");
            var errorMessage = new ChatMessage
            {
                Content = "抱歉，系统暂时无法处理您的请求，请稍后重试。",
                IsUser = false,
                Timestamp = DateTime.Now
            };
            _chatHistory.Add(errorMessage);
            return errorMessage.Content;
        }
    }

    public async Task<List<ChatMessage>> GetChatHistoryAsync()
    {
        await Task.CompletedTask; // 模拟异步操作
        return _chatHistory.ToList();
    }

    public async Task ClearChatHistoryAsync()
    {
        await Task.CompletedTask; // 模拟异步操作
        _chatHistory.Clear();
        _logger.LogInformation("Chat history cleared");
    }

    public async Task StartNewTopicAsync()
    {
        await Task.CompletedTask; // 模拟异步操作
        _chatHistory.Clear();
        _logger.LogInformation("New topic started, chat history cleared");
    }
}
